import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    list: [],
    inputValue: "",
    nextId: 5,
    dafaultValue:'all'
  },
  mutations: {
    initList(state, list) {
      state.list = list;
    },
    setInputValue(state, val) {
      // 为store中的value复制
      state.inputValue = val;
    },
    // 添加item项
    addItems(state) {
      const obj = {
        id: 0,
        info: state.inputValue.trim(),
        done: false
      };
      state.list.push(obj);
      state.nextId++;
      state.inputValue = "";
    },
    // 删除item项
    delete(state, id) {
      const index = state.list.findIndex(x => {
        return x.id === id;
      });
      state.list.splice(index, 1);
    },
    // 改变复选框的选中状态
    changeStatusBox(state, params) {
      const i = state.list.findIndex(x => {
        return x.id === params.id;
      });
      if (i !== -1) {
        state.list[i].done = params.status;
      }
    },
    // 清除已完成的
    clearItem(state){
      state.list= state.list.filter(x=>x.done===false);
    },

    doTag(state,value){
      state.dafaultValue=value;
    }
  },
  actions: {
    getList(context, data) {
      axios.get("/list.json").then(({ data }) => {
        console.log(data);
        context.commit("initList", data);
      });
    }
  },
  // 对数据进行包装
  getters: {
    // 统计未完成的数量
    unDoChange(state) {
      return state.list.filter(x => x.done === false).length;
    },
    infoList(state){
      if(state.dafaultValue==='all'){
        return state.list;
      }

      if(state.dafaultValue==='undone'){
        return state.list.filter(x=>!x.done);
      }

      if(state.dafaultValue==='done'){
        return state.list.filter(x=>x.done);
      }
      return state.list;
    }
  },
  modules: {}
});
